package com.taotao.order.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbOrderItemMapper;
import com.taotao.mapper.TbOrderMapper;
import com.taotao.mapper.TbOrderShippingMapper;
import com.taotao.order.dao.JedisClient;
import com.taotao.order.pojo.Order;
import com.taotao.pojo.TbOrderItem;
import com.taotao.pojo.TbOrderShipping;
@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private TbOrderMapper orderMapper;
	@Autowired
	private TbOrderItemMapper orderItemMapper;
	@Autowired
	private TbOrderShippingMapper orderShippingMapper;
	@Autowired
	private JedisClient jedisClient;
	
	@Value("${ORDER_GEN_KEY}")
	private String ORDER_GEN_KEY;
	@Value("${ORDER_INIT_ID}")
	private String ORDER_INIT_ID;
	@Value("${ORDER_DETAIL_GEN_KEY}")
	private String ORDER_DETAIL_GEN_KEY;
	
	@Override
	public TaotaoResult createOrder(Order order) {
		// TODO Auto-generated method stub
		
		
		
		
		String string = jedisClient.get(ORDER_GEN_KEY);
		if (string == null) {
			string = jedisClient.set(ORDER_GEN_KEY, ORDER_INIT_ID);
		}
		long orderId = jedisClient.incr(ORDER_GEN_KEY);
		
		order.setOrderId(orderId+"");
		order.setStatus(1);
		Date date = new Date();
		order.setCreateTime(date);
		order.setUpdateTime(date);
		order.setBuyerRate(0);
		orderMapper.insert(order);
		
		List<TbOrderItem> orderItems = order.getOrderItems();
		for (TbOrderItem orderItem : orderItems) {
			long orderItemId = jedisClient.incr(ORDER_DETAIL_GEN_KEY);
			orderItem.setId(orderItemId+"");
			orderItem.setOrderId(orderId+"");
			orderItemMapper.insert(orderItem);
		}
		
		TbOrderShipping orderShipping = order.getOrderShipping();
		orderShipping.setOrderId(orderId+"");
		orderShipping.setUpdated(date);
		orderShipping.setCreated(date);
		
		orderShippingMapper.insert(orderShipping);
		
		
		
		return TaotaoResult.ok(orderId);
	}

	
	
}
